package com.eques.demo.adapter

/**
 * @author Create by yc on 2025/10/29/Wed 10:44
 * @description
 */
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.eques.bean.RingRecord
import com.eques.demo.R

class RingRecordAdapter : RecyclerView.Adapter<RingRecordAdapter.ViewHolder>() {

    private var ringRecords: List<RingRecord> = emptyList()

    // 点击监听器
    var onItemClickListener: ((RingRecord) -> Unit)? = null

    fun setData(records: List<RingRecord>) {
        this.ringRecords = records
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_ring_record, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val record = ringRecords[position]
        holder.bind(record)

        holder.itemView.setOnClickListener {
            onItemClickListener?.invoke(record)
        }
    }

    override fun getItemCount(): Int = ringRecords.size

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val ivThumbnail: ImageView = itemView.findViewById(R.id.iv_thumbnail)
        private val tvOpenMethod: TextView = itemView.findViewById(R.id.tv_open_method)
        private val tvTime: TextView = itemView.findViewById(R.id.tv_time)
        private val tvDeviceId: TextView = itemView.findViewById(R.id.tv_device_id)

        fun bind(record: RingRecord) {
            // 加载缩略图
            if (record.has_preview == 1) {
                Glide.with(itemView.context)
                    .load(record.getThumbnailUrl())
                    .placeholder(R.drawable.ic_person)
                    .error(R.drawable.ic_person)
                    .into(ivThumbnail)
            } else {
                ivThumbnail.setImageResource(R.drawable.ic_person)
            }

            // 设置开锁方式
            tvOpenMethod.text = record.getOpenLockMethod()

            // 设置时间
            tvTime.text = record.getFormattedTime()

            // 可选：显示设备ID（调试用）
            // tvDeviceId.text = "设备: ${record.bid.take(8)}..."
        }
    }
}
